package org.base.common.util;

import org.base.common.util.crypto.RandomNumberGenerator;
import org.base.common.util.crypto.SecureRandomNumberGenerator;
import org.base.common.util.crypto.SimpleHash;

import java.security.NoSuchAlgorithmException;

/**
 * @author He mingliang
 * @date 2020/6/2
 */
public class PasswordHelper {

    private static final RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();


    private static SimpleHash simpleHash = null;

    private static final String ALGORITHM_NAME = "md5";

    private static final int HASH_ITERATIONS = 1024;

    /**
     * 加密的盐
     *
     * @return
     */
    public static String getSalt() {
        return randomNumberGenerator.nextString();
    }

    /**
     * 加密
     *
     * @param source
     * @param salt
     * @return
     */
    public static String encryption(String source, String salt) throws NoSuchAlgorithmException {
        return new SimpleHash(ALGORITHM_NAME, source, salt, HASH_ITERATIONS).toBase64();
    }

    /**
     * 验证密码
     *
     * @param password 明文密码
     * @param salt
     * @param targetPassword 加密密码
     * @return
     */
    public static boolean checkPassword(String password, String salt, String targetPassword) throws NoSuchAlgorithmException {
        return encryption(password, salt).equals(targetPassword);
    }
}
